<!-- 农场产品邮寄记录 -->
<template>
    <div>
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row type="flex" justify="space-between" :gutter="48">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="仓库信息">
                            <a-select v-model="storehouseId" placeholder="请选择" @change="getData()">
                                <a-select-option v-for="(item,i) in storeList" :key="i" :value="item.storehouseId">{{item.storehouseName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8">
                        <a-form-item label="昵称">
                            <a-input v-model="nickname" allow-clear placeholder="请输入昵称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8">
                        <a-form-item label="类型">
                            <a-select v-model="type" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in typeList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8">
                        <a-form-item label="状态">
                            <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="16">
                    </a-col>
                    <a-col :md="8">
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <a-button icon="plus" @click="add()">新增</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ pageSize: size, total: total ,showSizeChanger: true}" size="small">
            <div slot="nickname" slot-scope="nickname,record">
                <a-avatar v-if="record.headimgurl" :src="record.headimgurl" />
                <span>  {{nickname}}</span>
            </div>
            <div slot="province" slot-scope="province,record">
                <div>{{province}}-{{record.city}}</div>
            </div>
           <div slot="storehouseId" slot-scope="storehouseId">
                <div v-for="(item,i) in storeList" :key="i">
                    <a-tag v-if="item.storehouseId == storehouseId" :color="colors[i%13]">{{item.storehouseName}}</a-tag>
                </div>
            </div>
            <div slot="type" slot-scope="type">
                <div v-for="(item,i) in typeList" :key="i">
                    <a-tag v-if="item.id == type" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="展示" un-checked-children="隐藏" disabled :checked="status == 1 ? true : false" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button type="link">删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>

        <!-- 添加、修改购买记录 -->
        <a-modal
            title="添加、修改商品购买记录"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="所在仓库">
                        <a-select v-model="item.storehouseId" placeholder="请选择">
                            <a-select-option v-for="(itm) in storeList" :value="itm.storehouseId" :key="itm.storehouseId">{{itm.storehouseName}}</a-select-option>
                        </a-select>       
                    </a-form-item>
                    <a-form-item label="昵称">
                        <a-input v-model="item.nickname" placeholder="请输入昵称" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="省份">
                        <a-select v-model="provinces" placeholder="请选择" allowClear @change="selProvince">
                            <a-select-option v-for="(item,i) in provinceList" :key="i" :value="item.value">{{item.label}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="城市">
                        <a-select v-model="item.city" placeholder="请选择" allowClear>
                            <a-select-option v-for="(item,i) in cityList" :key="i" :value="item.label">{{item.label}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="购买时间" >
                        <a-date-picker show-time v-model="item.purchaseTime" placeholder="选择购买时间" />
                    </a-form-item>
                    <a-form-item label="用户头像">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="是否展示">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryGoodsPurchaseRecord , updateGoodsPurchaseRecord , queryGoodsStorehouseBindConfig } from '@/api/newMall';
import moment from 'moment';
import area from '@/assets/area';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            isload: false,
            visible: false,
            dataList: [],
            columns,
            nickname: '', // 昵称
            type: undefined,
            typeList: [
                { id: '0', name: '手动添加'},
                { id: '1', name: '真实购买'},
            ],
            status: undefined,
            statusList: [
                { id: '0', name: '隐藏'},
                { id: '1', name: '展示'},
            ],
            page: 1,
            total: 0,
            size: 10,
            confirmLoading: false,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            item: {
                id: '',
                nickname: '', // 昵称
                province: undefined, // 省份
                city: undefined, // 城市
                storehouseId: undefined, // 所在仓库
                purchaseTime: '', // 购买时间
                status: '1', // 是否展示
            },
            fileList: [],
            provinceList: [],
            provinces: '',
            cityList: [],
            storehouseId: undefined,
            storeList: [],
            userId: sessionStorage.getItem('userId'),
        };
    },
    async created(){
        try {
            var list = []
            for (const key in area.province_list) {
                if (area.province_list.hasOwnProperty(key)) {
                    list.push({
                        'label': area.province_list[key],
                        'value': `${key},${area.province_list[key]}`,
                        isLeaf: false,
                    })
                }
            }
            this.provinceList = list;
            await this._queryGoodsStorehouseBindConfig();
            this.getData()
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: '网路丢失，请稍后再试！',
                duration: 8,
            })
        }
    },
    methods: {
        moment,
        // 查询用户所包含的仓库信息
        _queryGoodsStorehouseBindConfig(){
            let _this = this;
            return new Promise((resolve,reject) => {
                queryGoodsStorehouseBindConfig({userId: _this.userId,size: 99})
                .then(res => {
                    if(res.success){
                        _this.storeList = res.data.content;
                        _this.storehouseId = res.data.content.length > 0 ? res.data.content[0].storehouseId : '';
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 查询数据
        getData(){
            let _this = this
            const params = {
                'brandId': _this.brandId,
                'nickname': _this.nickname,
                'type': _this.type,
                'status': _this.status,
                'storehouseId': _this.storehouseId,
                'size':_this.size,
                'page':_this.page - 1,
            }
            _this.isload = true
            queryGoodsPurchaseRecord(params)
            .then(res=>{
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content
                    _this.total = res.data.totalElements;
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.item.id = ''
            this.item.nickname = ''
            this.item.province = undefined;
            this.provinces = undefined;
            this.item.city = undefined;
            this.item.purchaseTime = ''
            this.item.status = '1';
            this.item.storehouseId = this.storehouseId;
            this.fileList = [];
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item))
            let _this = this;
            for (const key in area.province_list) {
                if (area.province_list.hasOwnProperty(key)) {
                    if(area.province_list[key].indexOf(item.province) != -1){
                        _this.provinces = `${key},${area.province_list[key]}`;
                    }
                }
            }
            _this.selProvince('1');
            this.fileList = [];
            this.visible = true;
        },
        // 选择图片
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        // 确定添加、修改
        handleOk(){
            let _this = this
            if(_this.item.nickname == ''){
                _this.$message.warning('请输入购买用户昵称');
                return
            }
            if(_this.item.province === undefined){
                _this.$message.warning('请选择省份');
                return
            }
            if(_this.item.city === undefined){
                _this.$message.warning('请选择城市');
                return
            }
            if(_this.item.purchaseTime == ''){
                _this.$message.warning('请选择购买时间');
                return
            }
            _this.confirmLoading = true;
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', _this.item.id);
            formData.append('nickname', _this.item.nickname);
            formData.append('province', _this.item.province);
            formData.append('city', _this.item.city);
            formData.append('purchaseTime', _this.item.purchaseTime);
            formData.append('storehouseId', _this.item.storehouseId);
            formData.append('status', _this.item.status);
            if(_this.fileList.length > 0){
                formData.append('file',_this.fileList[0].originFileObj)
            }
            updateGoodsPurchaseRecord(formData)
            .then(res=>{
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id == '' ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this;
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', item.id);
            formData.append('isDelete', '1');
            updateGoodsPurchaseRecord(formData)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        datePickChange(value, dateString) {
            console.log('Selected Time: ', value);
            console.log('Formatted Selected Time: ', dateString);
        },
        datePickOk(value) {
            console.log('onOk: ', value);
        },
        // 选择省份
        selProvince(type){
            if(type != '1'){
                this.item.city = undefined;
            }
            if(this.provinces){
                this.item.province = this.provinces.split(',')[1]
                var provinceId = this.provinces.split(',')[0]
                console.log(provinceId,'provinceId')
                var list = [];
                for (const key in area.city_list) {
                    // console.log(key,'key')
                    if (area.city_list.hasOwnProperty(key) && key.substring(0, 2) == provinceId.substring(0,2)) {
                        list.push({
                            'label': area.city_list[key],
                            'value': `${area.city_list[key]}`,
                            isLeaf: false,
                        })
                    }
                }
                this.cityList = list;
            }else{
                this.province = ''
                this.cityList = [];
            }
        },
    }
}

</script>
<style scoped>

</style>